{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# vendor_scheduling_sat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/examples/vendor_scheduling_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/python/vendor_scheduling_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "Solves a simple shift scheduling problem.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Sequence\n",
    "from ortools.sat.python import cp_model\n",
    "\n",
    "\n",
    "class SolutionPrinter(cp_model.CpSolverSolutionCallback):\n",
    "    \"\"\"Print intermediate solutions.\"\"\"\n",
    "\n",
    "    def __init__(\n",
    "        self,\n",
    "        num_vendors,\n",
    "        num_hours,\n",
    "        possible_schedules,\n",
    "        selected_schedules,\n",
    "        hours_stat,\n",
    "        min_vendors,\n",
    "    ):\n",
    "        cp_model.CpSolverSolutionCallback.__init__(self)\n",
    "        self.__solution_count = 0\n",
    "        self.__num_vendors = num_vendors\n",
    "        self.__num_hours = num_hours\n",
    "        self.__possible_schedules = possible_schedules\n",
    "        self.__selected_schedules = selected_schedules\n",
    "        self.__hours_stat = hours_stat\n",
    "        self.__min_vendors = min_vendors\n",
    "\n",
    "    def on_solution_callback(self):\n",
    "        \"\"\"Called at each new solution.\"\"\"\n",
    "        self.__solution_count += 1\n",
    "        print(\"Solution %i: \", self.__solution_count)\n",
    "        print(\"  min vendors:\", self.__min_vendors)\n",
    "        for i in range(self.__num_vendors):\n",
    "            print(\n",
    "                \"  - vendor %i: \" % i,\n",
    "                self.__possible_schedules[self.value(self.__selected_schedules[i])],\n",
    "            )\n",
    "        print()\n",
    "\n",
    "        for j in range(self.__num_hours):\n",
    "            print(\"  - # workers on day%2i: \" % j, end=\" \")\n",
    "            print(self.value(self.__hours_stat[j]), end=\" \")\n",
    "            print()\n",
    "        print()\n",
    "\n",
    "    def solution_count(self):\n",
    "        \"\"\"Returns the number of solution found.\"\"\"\n",
    "        return self.__solution_count\n",
    "\n",
    "\n",
    "def vendor_scheduling_sat() -> None:\n",
    "    \"\"\"Create the shift scheduling model and solve it.\"\"\"\n",
    "    # Create the model.\n",
    "    model = cp_model.CpModel()\n",
    "\n",
    "    #\n",
    "    # data\n",
    "    #\n",
    "    num_vendors = 9\n",
    "    num_hours = 10\n",
    "    num_work_types = 1\n",
    "\n",
    "    traffic = [100, 500, 100, 200, 320, 300, 200, 220, 300, 120]\n",
    "    max_traffic_per_vendor = 100\n",
    "\n",
    "    # Last columns are :\n",
    "    #   index_of_the_schedule, sum of worked hours (per work type).\n",
    "    # The index is useful for branching.\n",
    "    possible_schedules = [\n",
    "        [1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 8],\n",
    "        [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 4],\n",
    "        [0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 2, 5],\n",
    "        [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 3, 4],\n",
    "        [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 4, 3],\n",
    "        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0],\n",
    "    ]\n",
    "\n",
    "    num_possible_schedules = len(possible_schedules)\n",
    "    selected_schedules = []\n",
    "    vendors_stat = []\n",
    "    hours_stat = []\n",
    "\n",
    "    # Auxiliary data\n",
    "    min_vendors = [t // max_traffic_per_vendor for t in traffic]\n",
    "    all_vendors = range(num_vendors)\n",
    "    all_hours = range(num_hours)\n",
    "\n",
    "    #\n",
    "    # Declare variables\n",
    "    #\n",
    "    x = {}\n",
    "\n",
    "    for v in all_vendors:\n",
    "        tmp = []\n",
    "        for h in all_hours:\n",
    "            x[v, h] = model.new_int_var(0, num_work_types, \"x[%i,%i]\" % (v, h))\n",
    "            tmp.append(x[v, h])\n",
    "        selected_schedule = model.new_int_var(\n",
    "            0, num_possible_schedules - 1, \"s[%i]\" % v\n",
    "        )\n",
    "        hours = model.new_int_var(0, num_hours, \"h[%i]\" % v)\n",
    "        selected_schedules.append(selected_schedule)\n",
    "        vendors_stat.append(hours)\n",
    "        tmp.append(selected_schedule)\n",
    "        tmp.append(hours)\n",
    "\n",
    "        model.add_allowed_assignments(tmp, possible_schedules)\n",
    "\n",
    "    #\n",
    "    # Statistics and constraints for each hour\n",
    "    #\n",
    "    for h in all_hours:\n",
    "        workers = model.new_int_var(0, 1000, \"workers[%i]\" % h)\n",
    "        model.add(workers == sum(x[v, h] for v in all_vendors))\n",
    "        hours_stat.append(workers)\n",
    "        model.add(workers * max_traffic_per_vendor >= traffic[h])\n",
    "\n",
    "    #\n",
    "    # Redundant constraint: sort selected_schedules\n",
    "    #\n",
    "    for v in range(num_vendors - 1):\n",
    "        model.add(selected_schedules[v] <= selected_schedules[v + 1])\n",
    "\n",
    "    # Solve model.\n",
    "    solver = cp_model.CpSolver()\n",
    "    solver.parameters.enumerate_all_solutions = True\n",
    "    solution_printer = SolutionPrinter(\n",
    "        num_vendors,\n",
    "        num_hours,\n",
    "        possible_schedules,\n",
    "        selected_schedules,\n",
    "        hours_stat,\n",
    "        min_vendors,\n",
    "    )\n",
    "    status = solver.solve(model, solution_printer)\n",
    "    print(\"Status = %s\" % solver.status_name(status))\n",
    "\n",
    "    print(\"Statistics\")\n",
    "    print(\"  - conflicts : %i\" % solver.num_conflicts)\n",
    "    print(\"  - branches  : %i\" % solver.num_branches)\n",
    "    print(\"  - wall time : %f s\" % solver.wall_time)\n",
    "    print(\"  - number of solutions found: %i\" % solution_printer.solution_count())\n",
    "\n",
    "\n",
    "def main(argv: Sequence[str]) -> None:\n",
    "    if len(argv) > 1:\n",
    "        raise app.UsageError(\"Too many command-line arguments.\")\n",
    "    vendor_scheduling_sat()\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
